import logging
import os
import shutil
import sys
import argparse
import time
import subprocess
import threading
from script import readconfig

SOURCE_DIR=os.path.split(os.path.realpath(__file__))[0]
BUILD_DIR=os.path.join(SOURCE_DIR, 'build')

def cmd_exec(command, _logger):
    _logger.info("executing command: {}".format(command))

    process = subprocess.Popen(
        command,
        shell=True,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        )

    for line in iter(process.stdout.readline, ""):
        if len(line) == 0:
            break
        else:
            _logger.info(line.strip())
    for line in iter(process.stderr.readline, ""):
        if len(line) == 0:
            break
        else:
            _logger.error(line.strip())
    try :
        ret = process.wait()
    except:
        _logger.error("command executed fail with exit-code={}: {}".format(ret, command))
    _logger.info("process finish")
    _logger.info("executed command with exit-code={}".format(ret))
    return ret

def clean():
    if os.path.exists(BUILD_DIR):
        shutil.rmtree(BUILD_DIR)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("--section", dest="section", nargs=1, help="section")
    parser.add_argument("-p", "--product", dest="product", nargs="*", help="product")
    parser.add_argument("-e", "--platform", dest="platform", nargs="*", help="platform")
    parser.add_argument("-c", "--component", dest="component", nargs="*", help="component")
    parser.add_argument("clean", nargs="?", help="clean")
    args = parser.parse_args()
    
    clean()
    if args.clean == "clean":
        print("clean success!")
        exit(0);
    
    os.mkdir(BUILD_DIR)
    os.chdir(BUILD_DIR)
    LOGGING_DIR=os.path.join(BUILD_DIR, 'logs')
    os.mkdir(LOGGING_DIR)
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    logger_filename=LOGGING_DIR+'/{}_{}.log'.format(time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()), args.section)
    logger_file = logging.FileHandler(logger_filename, encoding='utf-8')
    logger_format = logging.Formatter(fmt="%(asctime)s [CFTM][%(levelname)s]: %(message)s", datefmt='%Y-%m-%d %H:%M:%S')
    logger_file.setFormatter(logger_format)
    logger.addHandler(logger_file)
    console = logging.StreamHandler()
    console.setFormatter(logger_format)
    logger.addHandler(console)

    readconfig.readConfig(args.section, args.product, args.platform, args.component)
    cmake_cmd="cmake -S {}".format(SOURCE_DIR)
    cmd_exec(cmake_cmd, logger)